package com.ruoyi.system.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.info.PackageInfo;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * HarmonyOS应用包解析工具
 */
public final class HarmonyAppParser {
    // 配置文件路径常量
    private static final String MODULE_JSON = "module.json";
    private static final String PACK_INFO = "pack.info";
    private static final String MEDIA_DIR = "resources/base/media/";
    private static final Pattern IMAGE_PATTERN =
            Pattern.compile(".*\\.(png|jpg|jpeg|webp|bmp)$", Pattern.CASE_INSENSITIVE);

    /**
     * 解析HAP文件
     */
    public static PackageInfo parse(InputStream hapStream) throws IOException {
        // 先将输入流完整读取到字节数组
        byte[] hapData = IOUtils.toByteArray(hapStream);

        try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(hapData))) {
            PackageInfo info = new PackageInfo();
            boolean hasModuleJson = false;
            String iconPath = null;

            // 第一次遍历：解析配置文件和记录图标路径
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                String entryName = entry.getName();

                if (MODULE_JSON.equals(entryName)) {
                    parseModuleJson(IOUtils.toString(zis, StandardCharsets.UTF_8), info);
                    hasModuleJson = true;
                } else if (PACK_INFO.equals(entryName)) {
                    parsePackInfo(IOUtils.toString(zis, StandardCharsets.UTF_8), info);
                } else if (entryName.startsWith(MEDIA_DIR) && IMAGE_PATTERN.matcher(entryName).matches()) {
                    // 只记录第一个匹配的图标路径
                    if (iconPath == null) {
                        iconPath = entryName;
                        info.setIconName(iconPath);
                    }
                } else {
                    // 跳过其他文件内容
                    zis.skip(entry.getSize());
                }
            }

            if (!hasModuleJson) {
                throw new IllegalArgumentException("Invalid HAP: Missing module.json");
            }

            // 第二次遍历：读取图标内容（如果有图标路径）
            if (iconPath != null) {
                byte[] iconBytes = extractIconBytes(hapData, iconPath);
                info.setIconBytes(iconBytes);
            }

            return info;
        }
    }

    /**
     * 从HAP数据中提取指定路径的图标字节内容
     */
    private static byte[] extractIconBytes(byte[] hapData, String iconPath) throws IOException {
        try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(hapData))) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                if (iconPath.equals(entry.getName())) {
                    return IOUtils.toByteArray(zis);
                } else {
                    // 跳过不匹配的文件
                    zis.skip(entry.getSize());
                }
            }
        }
        return null;
    }

    // 解析module.json主配置
    private static void parseModuleJson(String json, PackageInfo info) {
        JSONObject root = JSON.parseObject(json);
        JSONObject app = root.getJSONObject("app");

        // 基础信息
        info.setPackageName(app.getString("bundleName"));
        info.setVersionnumber(app.getString("versionName"));
        info.setVersionCode(String.valueOf(app.getInteger("versionCode")));
        info.setDevSupplier(app.getString("vendor"));

        // API版本信息
        if (app.containsKey("minAPIVersion")) {
            info.setMinSystemVersion(String.valueOf(app.getInteger("minAPIVersion")));
        }
        if (app.containsKey("compileSdkVersion")) {
            info.setSdkRequirement(app.getString("compileSdkVersion"));
        }
    }

    // 解析pack.info备用配置
    private static void parsePackInfo(String json, PackageInfo info) {
        JSONObject root = JSON.parseObject(json);
        JSONObject summary = root.getJSONObject("summary");
        JSONObject app = summary.getJSONObject("app");

        // 仅补充主配置未提供的字段
        if (info.getPackageName() == null) {
            info.setPackageName(app.getString("bundleName"));
        }
        if (info.getVersionnumber() == null) {
            info.setVersionnumber(app.getJSONObject("version").getString("name"));
        }
        if (info.getMinSystemVersion() == null && !summary.getJSONArray("modules").isEmpty()) {
            JSONObject module = summary.getJSONArray("modules").getJSONObject(0);
            if (module.containsKey("apiVersion")) {
                JSONObject apiVersion = module.getJSONObject("apiVersion");
                if (apiVersion.containsKey("compatible")) {
                    info.setMinSystemVersion(String.valueOf(apiVersion.getInteger("compatible")));
                }
            }
        }
    }

    // 转换API版本格式（可选，根据需求使用）
    private static String formatApiVersion(int versionCode) {
        int major = versionCode / 10000000;
        int minor = (versionCode % 10000000) / 100000;
        return String.format("HarmonyOS %d.%d", major, minor);
    }
} 